<template>
  <div class="notice-management">
    <div class="page-header">
      <h1 class="page-title">通知管理</h1>
      <p class="page-desc">发布系统通知、课程通知、考试通知等，管理学生接收的所有通知信息</p>
    </div>

    <!-- 操作按钮 -->
    <el-card class="action-card" shadow="hover">
      <el-button type="primary" @click="handleCreate" :icon="Plus">
        发布新通知
      </el-button>
      <el-button @click="loadNotices" :icon="Refresh">
        刷新
      </el-button>
    </el-card>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="hover">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="通知类型">
          <el-select v-model="filterForm.noticeType" placeholder="全部" style="width: 150px" clearable>
            <el-option label="全部" value="" />
            <el-option label="系统通知" value="system" />
            <el-option label="课程通知" value="course" />
            <el-option label="考试通知" value="exam" />
            <el-option label="作业通知" value="homework" />
            <el-option label="一般通知" value="general" />
          </el-select>
        </el-form-item>
        <el-form-item label="学期">
          <el-select v-model="filterForm.semester" placeholder="全部" style="width: 150px" clearable>
            <el-option label="全部" value="" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2024秋季" />
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="全部" style="width: 150px" clearable>
            <el-option label="全部" value="" />
            <el-option label="草稿" :value="0" />
            <el-option label="已发布" :value="1" />
            <el-option label="已撤回" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="applyFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 通知列表 -->
    <el-card class="data-card" shadow="hover" v-loading="loading">
      <el-table :data="noticeList" stripe border>
        <el-table-column prop="noticeId" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getNoticeTypeColor(row.noticeType)" size="small">
              {{ getNoticeTypeText(row.noticeType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityColor(row.priority)" size="small">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="目标范围" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ getTargetScopeText(row.targetScope) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="semester" label="学期" width="100" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.publishTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)" size="small">查看</el-button>
            <el-button link type="warning" @click="handleEdit(row)" size="small" v-if="row.status !== 2">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑通知对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form :model="noticeForm" :rules="noticeRules" ref="noticeFormRef" label-width="100px">
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="noticeForm.title" placeholder="请输入通知标题" maxlength="200" show-word-limit />
        </el-form-item>
        
        <el-form-item label="通知内容" prop="content">
          <el-input 
            v-model="noticeForm.content" 
            type="textarea" 
            :rows="6" 
            placeholder="请输入通知内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="通知类型" prop="noticeType">
              <el-select v-model="noticeForm.noticeType" placeholder="请选择" style="width: 100%">
                <el-option label="系统通知" value="system" />
                <el-option label="课程通知" value="course" />
                <el-option label="考试通知" value="exam" />
                <el-option label="作业通知" value="homework" />
                <el-option label="一般通知" value="general" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="noticeForm.priority" placeholder="请选择" style="width: 100%">
                <el-option label="普通" :value="0" />
                <el-option label="重要" :value="1" />
                <el-option label="紧急" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="目标范围" prop="targetScope">
              <el-select v-model="noticeForm.targetScope" placeholder="请选择" style="width: 100%" @change="handleTargetScopeChange">
                <el-option label="全体学生" value="all" />
                <el-option label="指定班级" value="class" />
                <el-option label="指定学生" value="student" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学期" prop="semester">
              <el-select v-model="noticeForm.semester" placeholder="请选择学期" style="width: 100%">
                <el-option label="2025春季" value="2025春季" />
                <el-option label="2024秋季" value="2024秋季" />
                <el-option label="2024春季" value="2024春季" />
                <el-option label="2024秋季" value="2024秋季" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="目标对象" v-if="noticeForm.targetScope === 'class'" prop="targetIds">
          <el-select v-model="selectedClasses" multiple placeholder="请选择班级" style="width: 100%">
            <el-option
              v-for="clazz in classList"
              :key="clazz.clazzId"
              :label="clazz.clazzName"
              :value="clazz.clazzId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="目标对象" v-if="noticeForm.targetScope === 'student'" prop="targetIds">
          <el-select v-model="selectedStudents" multiple placeholder="请选择学生" style="width: 100%" filterable>
            <el-option
              v-for="student in studentList"
              :key="student.studentId"
              :label="`${student.stuName} (${student.stuNo})`"
              :value="student.studentId"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleSaveDraft" v-if="!noticeForm.noticeId">保存草稿</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePublish">发布通知</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看通知详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="通知详情" width="700px">
      <div class="notice-detail">
        <h2>{{ currentNotice.title }}</h2>
        <div class="detail-meta">
          <el-tag :type="getNoticeTypeColor(currentNotice.noticeType)" size="small">
            {{ getNoticeTypeText(currentNotice.noticeType) }}
          </el-tag>
          <el-tag :type="getPriorityColor(currentNotice.priority)" size="small">
            {{ getPriorityText(currentNotice.priority) }}
          </el-tag>
          <el-tag size="small">{{ getTargetScopeText(currentNotice.targetScope) }}</el-tag>
          <el-tag :type="getStatusColor(currentNotice.status)" size="small">
            {{ getStatusText(currentNotice.status) }}
          </el-tag>
        </div>
        <div class="detail-info">
          <p><strong>发布者：</strong>{{ currentNotice.publisherName }}</p>
          <p><strong>学期：</strong>{{ currentNotice.semester || '无' }}</p>
          <p><strong>发布时间：</strong>{{ formatTime(currentNotice.publishTime) }}</p>
        </div>
        <div class="detail-content">
          <strong>通知内容：</strong>
          <p>{{ currentNotice.content }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import request from '../utils/request'

const loading = ref(false)
const noticeList = ref([])
const classList = ref([])
const studentList = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 筛选表单
const filterForm = reactive({
  noticeType: '',
  semester: '',
  status: ''
})

// 通知表单
const noticeForm = reactive({
  noticeId: null,
  title: '',
  content: '',
  publisherType: 'admin',
  publisherId: null,
  publisherName: '',
  targetScope: 'all',
  targetIds: '',
  noticeType: 'general',
  priority: 0,
  semester: '',
  status: 1
})

const selectedClasses = ref([])
const selectedStudents = ref([])

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('发布新通知')
const viewDialogVisible = ref(false)
const currentNotice = ref({})
const noticeFormRef = ref(null)

// 表单验证规则
const noticeRules = {
  title: [
    { required: true, message: '请输入通知标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入通知内容', trigger: 'blur' }
  ],
  noticeType: [
    { required: true, message: '请选择通知类型', trigger: 'change' }
  ],
  targetScope: [
    { required: true, message: '请选择目标范围', trigger: 'change' }
  ],
  semester: [
    { required: true, message: '请选择学期', trigger: 'change' }
  ]
}

// 获取当前管理员信息
const user = JSON.parse(localStorage.getItem('user') || '{}')

// 加载通知列表
const loadNotices = async () => {
  loading.value = true
  try {
    const response = await request.get('/api/admin/notices', {
      params: {
        publisherType: 'admin',
        publisherId: user.adminId,
        noticeType: filterForm.noticeType || null,
        semester: filterForm.semester || null,
        status: filterForm.status !== '' ? filterForm.status : null,
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      }
    })
    if (response.code === 200) {
      noticeList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取通知列表失败')
    }
  } catch (error) {
    console.error('获取通知列表失败:', error)
    ElMessage.error('获取通知列表失败')
  } finally {
    loading.value = false
  }
}

// 加载班级列表
const loadClasses = async () => {
  try {
    const response = await request.get('/api/admin/clazz/list')
    if (response.code === 200) {
      classList.value = response.data || []
    }
  } catch (error) {
    console.error('获取班级列表失败:', error)
  }
}

// 加载学生列表
const loadStudents = async () => {
  try {
    const response = await request.get('/api/admin/student/list')
    if (response.code === 200) {
      studentList.value = response.data || []
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
  }
}

// 应用筛选
const applyFilter = () => {
  pagination.currentPage = 1
  loadNotices()
}

// 重置筛选
const resetFilter = () => {
  filterForm.noticeType = ''
  filterForm.semester = ''
  filterForm.status = ''
  pagination.currentPage = 1
  loadNotices()
}

// 创建通知
const handleCreate = () => {
  dialogTitle.value = '发布新通知'
  resetNoticeForm()
  dialogVisible.value = true
}

// 编辑通知
const handleEdit = (row) => {
  dialogTitle.value = '编辑通知'
  Object.assign(noticeForm, row)
  
  // 如果有目标ID，转换为数组
  if (row.targetIds) {
    if (row.targetScope === 'class') {
      selectedClasses.value = row.targetIds.split(',').map(id => parseInt(id))
    } else if (row.targetScope === 'student') {
      selectedStudents.value = row.targetIds.split(',').map(id => parseInt(id))
    }
  }
  
  dialogVisible.value = true
}

// 查看通知
const handleView = (row) => {
  currentNotice.value = row
  viewDialogVisible.value = true
}

// 删除通知
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await request.delete(`/api/admin/notice/${row.noticeId}`)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadNotices()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 目标范围改变
const handleTargetScopeChange = () => {
  selectedClasses.value = []
  selectedStudents.value = []
  noticeForm.targetIds = ''
}

// 保存草稿
const handleSaveDraft = async () => {
  if (!noticeFormRef.value) return
  
  await noticeFormRef.value.validate(async (valid) => {
    if (valid) {
      noticeForm.status = 0 // 草稿状态
      await saveNotice()
    }
  })
}

// 发布通知
const handlePublish = async () => {
  if (!noticeFormRef.value) return
  
  await noticeFormRef.value.validate(async (valid) => {
    if (valid) {
      // 处理目标ID
      if (noticeForm.targetScope === 'class' && selectedClasses.value.length > 0) {
        noticeForm.targetIds = selectedClasses.value.join(',')
      } else if (noticeForm.targetScope === 'student' && selectedStudents.value.length > 0) {
        noticeForm.targetIds = selectedStudents.value.join(',')
      } else if (noticeForm.targetScope === 'all') {
        noticeForm.targetIds = ''
      } else if (noticeForm.targetScope !== 'all') {
        ElMessage.warning('请选择目标对象')
        return
      }

      noticeForm.status = 1 // 已发布状态
      noticeForm.publishTime = new Date()
      await saveNotice()
    }
  })
}

// 保存通知
const saveNotice = async () => {
  try {
    // 设置发布者信息
    noticeForm.publisherType = 'admin'
    noticeForm.publisherId = user.adminId
    noticeForm.publisherName = user.adminName || '系统管理员'

    const url = noticeForm.noticeId ? '/api/admin/notice/update' : '/api/admin/notice/create'
    const response = await request.post(url, noticeForm)
    
    if (response.code === 200) {
      ElMessage.success(noticeForm.status === 0 ? '草稿保存成功' : '发布成功')
      dialogVisible.value = false
      loadNotices()
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 重置表单
const resetNoticeForm = () => {
  Object.assign(noticeForm, {
    noticeId: null,
    title: '',
    content: '',
    publisherType: 'admin',
    publisherId: null,
    publisherName: '',
    targetScope: 'all',
    targetIds: '',
    noticeType: 'general',
    priority: 0,
    semester: '',
    status: 1
  })
  selectedClasses.value = []
  selectedStudents.value = []
  if (noticeFormRef.value) {
    noticeFormRef.value.clearValidate()
  }
}

// 对话框关闭
const handleDialogClose = () => {
  resetNoticeForm()
}

// 分页
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadNotices()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadNotices()
}

// 辅助方法
const getNoticeTypeText = (type) => {
  const map = {
    'system': '系统通知',
    'course': '课程通知',
    'exam': '考试通知',
    'homework': '作业通知',
    'general': '一般通知'
  }
  return map[type] || type
}

const getNoticeTypeColor = (type) => {
  const map = {
    'system': 'danger',
    'course': 'primary',
    'exam': 'warning',
    'homework': 'success',
    'general': 'info'
  }
  return map[type] || ''
}

const getPriorityText = (priority) => {
  const map = {
    0: '普通',
    1: '重要',
    2: '紧急'
  }
  return map[priority] || priority
}

const getPriorityColor = (priority) => {
  const map = {
    0: 'info',
    1: 'warning',
    2: 'danger'
  }
  return map[priority] || ''
}

const getTargetScopeText = (scope) => {
  const map = {
    'all': '全体学生',
    'class': '指定班级',
    'student': '指定学生'
  }
  return map[scope] || scope
}

const getStatusText = (status) => {
  const map = {
    0: '草稿',
    1: '已发布',
    2: '已撤回'
  }
  return map[status] || status
}

const getStatusColor = (status) => {
  const map = {
    0: 'info',
    1: 'success',
    2: 'danger'
  }
  return map[status] || ''
}

const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

onMounted(() => {
  loadNotices()
  loadClasses()
  loadStudents()
})
</script>

<style scoped>
.notice-management {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.page-desc {
  font-size: 14px;
  color: #6c757d;
}

.action-card {
  margin-bottom: 16px;
  border-radius: 12px;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.data-card {
  border-radius: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.notice-detail h2 {
  font-size: 24px;
  color: #2c3e50;
  margin-bottom: 16px;
}

.detail-meta {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.detail-info {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.detail-info p {
  margin: 8px 0;
  color: #495057;
}

.detail-content {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  line-height: 1.8;
}

.detail-content p {
  margin-top: 8px;
  color: #2c3e50;
  white-space: pre-wrap;
}
</style>

